# coding:utf-8
import json
from typing import Union

from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name
from qfluentwidgets import TextEdit, qconfig, Theme, setFont


class HighlighterTextEdit(TextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._lexer_name = 'json'
        self._light_style = 'solarized-light'
        self._dark_style = 'solarized-dark'
        qconfig.themeChanged.connect(self.__onThemeChanged)
        setFont(self, 18)

    def __onThemeChanged(self, theme: Theme):
        text = self.toPlainText()
        self._highlight(text)

    def setLexer(self, lexer_name: str):
        self._lexer_name = lexer_name

    def lexer(self) -> str:
        return self._lexer_name

    def setJson(self, json_str: Union[str, dict]):
        self.setLexer('json')
        if isinstance(json_str, dict):
            json_str = json.dumps(json_str, indent=4, ensure_ascii=False)
        self._highlight(json_str)

    def _highlight(self, text: str):
        lexer = get_lexer_by_name(self._lexer_name)
        formatter = HtmlFormatter(
            full=True,
            style=self._light_style if qconfig.theme == Theme.LIGHT else self._dark_style,
            noclasses=True,
            nobackground=True
        )
        html = highlight(text, lexer, formatter)
        self.setHtml(html)

    def setPython(self, text: str):
        self.setLexer('python')
        self._highlight(text)


if __name__ == '__main__':
    from PyQt6.QtWidgets import QApplication
    app = QApplication([])
    te = HighlighterTextEdit()
    tt = r'''
Traceback (most recent call last):
  File "F:\PythonObject\python-tools-box\components\widgets\text_edit.py", line 50, in <module>
    w
NameError: name 'w' is not defined
    '''
    te.setPython(tt)
    te.show()
    app.exec()

